class MealRecord {
  final String id;
  final DateTime timestamp;
  final String mealType; // 早餐、午餐、晚餐、加餐
  final List<FoodItem> foods;
  final String? notes;

  MealRecord({
    required this.id,
    required this.timestamp,
    required this.mealType,
    required this.foods,
    this.notes,
  });

  // 获取总热量
  double get totalCalories =>
      foods.fold(0, (sum, food) => sum + food.calories * food.quantity);

  // 从JSON转换和转为JSON的方法
  factory MealRecord.fromJson(Map<String, dynamic> json) {
    return MealRecord(
      id: json['id'],
      timestamp: DateTime.parse(json['timestamp']),
      mealType: json['mealType'],
      foods: (json['foods'] as List)
          .map((item) => FoodItem.fromJson(item))
          .toList(),
      notes: json['notes'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'timestamp': timestamp.toIso8601String(),
      'mealType': mealType,
      'foods': foods.map((food) => food.toJson()).toList(),
      'notes': notes,
    };
  }
}

class FoodItem {
  final String name;
  final double quantity; // 份数或重量
  final String unit; // 单位（克、份等）
  final double calories; // 每单位的卡路里
  final double? protein; // 蛋白质(g)
  final double? fat; // 脂肪(g)
  final double? carbs; // 碳水化合物(g)

  FoodItem({
    required this.name,
    required this.quantity,
    required this.unit,
    required this.calories,
    this.protein,
    this.fat,
    this.carbs,
  });

  factory FoodItem.fromJson(Map<String, dynamic> json) {
    return FoodItem(
      name: json['name'],
      quantity: json['quantity'],
      unit: json['unit'],
      calories: json['calories'],
      protein: json['protein'],
      fat: json['fat'],
      carbs: json['carbs'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'quantity': quantity,
      'unit': unit,
      'calories': calories,
      'protein': protein,
      'fat': fat,
      'carbs': carbs,
    };
  }
}
